<template>
  <view class="page-container bg-ff">
    <u-notify ref="notify"></u-notify>
    <u-tabs class="w-full" :list="[{name:'答题模式'},{name:'背题模式'}]"
            :current="tabIndex"
            :activeStyle="{
            color: '#87ADFF',
            fontWeight: 'bold',
            transform: 'scale(1.05)'
            }"
            :itemStyle="{
              width: '100%',
              padding: '26rpx 0',
              flex: 1,
            }"
            @click="onTabChange"
    ></u-tabs>
    <view class="border-b-1 border-dd relative top10"></view>
    <swiper class="page-body" :current="currentIndex" @change="onSwiperChange">
        <swiper-item v-for="(item, index) in list" :key="index">
          <view v-if="index<=currentIndex+2 && index>=currentIndex-2">
            <view class="py-32 px-24 font-32 lh-48">
              <text>{{index+1}}、</text>
              <image :src="questionType[item.type_name]" class="w-72 h-34 relative top-6 right-4" />{{ item.question }}
            </view>
            <view v-for="(value, label, index) in item.options" :key="index" @click="onRadioChange(label,item)">
              <view class="py-32 px-24 bg-ff flex items-center" :class="{'bg-f7':index%2 ===0}" v-if="tabIndex===0">
                <image src="/static/images/success.png" class="icon-40" v-if="item.down&&label==item.answer"></image>
                <image src="/static/images/error.png" class="icon-40" v-if="label==item.down&&label!=item.answer"></image>
                <view class="border border-dd icon-40 rounded-full flex items-center justify-center" v-if="(label!=item.down&&label!=item.answer)|| !item.down">{{label}}</view>
                <view class="flex-1 pl-24" :class="{'text-FF1515':label==item.down&&label!=item.answer, 'text-00EE77':item.down&&label==item.answer}">{{value}}</view>
              </view>
              <view class="py-32 px-24 bg-ff flex items-center" :class="{'bg-f7':index%2 ===0}" v-if="tabIndex===1">
                <image src="/static/images/success.png" class="icon-40" v-if="label==item.answer"></image>
                <image src="/static/images/error.png" class="icon-40" v-if="label==item.down&&label!=item.answer"></image>
                <view class="border border-dd icon-40 rounded-full flex items-center justify-center" v-if="(label!=item.down&&label!=item.answer)|| (!item.down&&label !=item.answer)">{{label}}</view>
                <view class="flex-1 pl-24" :class="{'text-FF1515':label==item.down&&label!=item.answer, 'text-00EE77':(item.down&&label==item.answer)|| label==item.answer}">{{value}}</view>
              </view>
            </view>
            <view class="pt-48" v-if="list[currentIndex]?.down&&tabIndex===0">
              <view class="box-shadows p-24 bg-ff rounded-12 flex items-center justify-around">
                <view>
                  <view class="text-center text-77">参考答案</view>
                  <view class="text-center text-success">{{list[currentIndex]?.answer}}</view>
                </view>
                <view >
                  <view class="text-center text-77">您的答案</view>
                  <view class="text-center">{{list[currentIndex]?.down}}</view>
                </view>
                <view>
                  <view class="text-center text-77">试题难度</view>
                  <view class="text-center text-primary">{{levelType[list[currentIndex]?.difficulty_level]}}</view>
                </view>
              </view>
            </view>
            <view class="pt-32 pb-12 px-24 text-77" v-if="list[currentIndex]?.down || tabIndex===1">
              <view class="flex items-center font-28 text-00 mb-24">
                <view class="h-24 w-6 bg-primary mr-10 "></view>
                试题解析
              </view>
              <view class="pl-12 mb-24" v-if="tabIndex===1">参考答案：<text class="text-success">{{list[currentIndex].answer}}</text></view>
              <view class="pl-12 pb-12" v-if="tabIndex===1&&list[currentIndex]?.comments">题目解析：</view>
              <view class="pl-12 font-26 text-3f">{{list[currentIndex]?.comments}}</view>
            </view>
          </view>
        </swiper-item>
      </swiper>
    <view class="box-shadows flex items-center justify-between px-32">
      <view class="flex items-center font-28 text-success py-32" @click="showDialog=true">
        <image src="/static/images/q_answer_sheet_right.png" class="icon-36 mr-12"/>
        {{successCount.length}}
      </view>
      <view class="flex items-center font-28 text-FF1515 py-32" @click="showDialog=true">
        <image src="/static/images/q_answer_sheet_wrong.png" class="icon-36 mr-12"/>
        {{errorCount.length}}
      </view>
      <view class="flex items-center font-28 py-32" @click="showDialog=true">
        <image src="/static/images/q_answer_sheet_number.png" class="icon-36 mr-12"/>
        {{currentIndex+1}}/{{list.length}}
      </view>
      <view class="flex items-center font-28 py-32" @click="addCollect" v-if="istype !==4">
        <image :src="list[currentIndex]?.collect ? '/static/images/star-active.png' : '/static/images/nav_test_icon_fav.png'" class="icon-36 mr-12"/>
         {{list[currentIndex]?.collect ? '已收藏' : '收藏'}}
      </view>
      <view class="flex items-center font-28 py-32" @click="addCollectCuoTi" v-if="istype ===4">
        <image src="/static/images/delete.png" class="icon-36 mr-12"/>
         清除
      </view>
    </view>
    <u-popup :show="showDialog" @close="showDialog=false" :round="10">
      <view class="p-32">
        <view class="flex items-center justify-between ">
          <view class="flex items-center font-28 text-success " @click="showDialog=false">
            <image src="/static/images/q_answer_sheet_right.png" class="icon-36 mr-12"/>
            {{successCount.length}}
          </view>
          <view class="flex items-center font-28 text-FF1515 " @click="showDialog=false">
            <image src="/static/images/q_answer_sheet_wrong.png" class="icon-36 mr-12"/>
            {{errorCount.length}}
          </view>
          <view class="flex items-center font-28 " @click="showDialog=false">
            <image src="/static/images/q_answer_sheet_number.png" class="icon-36 mr-12"/>
            {{currentIndex+1}}/{{list.length}}
          </view>
          <view class="flex items-center font-28 " @click="clearRecord" v-if="!istype">
            <image src="/static/images/delete.png" class="icon-36 mr-12"/>
            清空记录
          </view>
          <view class="flex items-center font-28 " @click="clearShoucang" v-if="istype===3">
            <image src="/static/images/delete.png" class="icon-36 mr-12"/>
             清空收藏
          </view>
          <view class="flex items-center font-28 " @click="clearCuoTi" v-if="istype===4">
            <image src="/static/images/delete.png" class="icon-36 mr-12"/>
            清空错题
          </view>
        </view>
      </view>
      <scroll-view class="min-h-700 max-h-900" scroll-y>
         <view class="grid-box6 px-32 pb-32">
           <view class="w-100 h-100 border border-dd rounded-full flex items-center justify-center" @click="currentIndex=index;showDialog=false" v-for="(item, index) in list" :key="index"
            :class="{
             'border-fb9191 color-fb9191 bg-fedddd':item.down&&item.down!=item.answer,
              'border-72dd70 color-72dd70 bg-daf6da':item.down==item.answer,
              'border-87 text-primary':index===currentIndex,
           }"
           >
             <view class="">{{index+1}}</view>
           </view>
         </view>
      </scroll-view>
    </u-popup>
    <u-popup :show="useStore.isPrompt" @close="useStore.isPrompt=false" mode="center" bgColor="transparent" overlayOpacity="0.8">
          <view class="text-ff">
              <view class='flex items-center'>
                <image src='/static/images/left_slide.png' class="w-84 h-76 zuo"></image>
                <view class="mx-24"> 手指左右滑动切题 </view>
                <image src='/static/images/right_slide.png' class="w-84 h-76 you"></image>
              </view>
            <view class="h-200"></view>
            <view class='border border-ff w-full px-24 py-24 text-center rounded-48' @click='useStore.isPrompt=false'>记住了 开始练习</view>
            <view class="h-200"></view>
			   </view>
		</u-popup>
  </view>
</template>
<script setup>
import { ref,computed,onMounted,nextTick } from 'vue'
import {onLoad} from "@dcloudio/uni-app"
import utils from '@/utils/utils.js'
import  {subject} from '@/api'
import useUserStore from '@/store/user.js'
const useStore = useUserStore()
import useExam from '@/common/useExam.js'

const {
  isTab,
  tabIndex,
  isotype,
  categoryId,
  count,
  currentIndex,
  list,
  questionType,
  levelType,
  errorCount,
  successCount,
  showDialog,
  storageArr,
  errorStorageArr,
  order2List,
  titleType,
  isShowError,
  addStorageApi
} = useExam();
const notify = ref(null)
const istype = ref(null)//3我的收藏 2我的错题
onLoad( async (options) => {
  console.log(options)
  if (options && options.type) {
    //顺序练习 || 随机练习
    isotype.value = Number(options.type)
    uni.setNavigationBarTitle({title: titleType[isotype.value]})
    if(options.isotype){
      //我的收藏 || 我的错题
      istype.value = Number(options.isotype)
      uni.setNavigationBarTitle({title: titleType[istype.value]})
    }
  }
  if (options && options.categoryId) {
    categoryId.value = options.categoryId
    await getStorageApi()
    await getQuestions()
  }
})

// 更改swiper当前项的回调
function onSwiperChange(e) {
  currentIndex.value = e.detail.current
}
// 单选题选项选择的回调
function onRadioChange(label,item) {
  console.log('label',label)
  console.log('item',item)
  // return
  if(tabIndex.value!==0) return
  if( list.value[currentIndex.value].down) return
  list.value[currentIndex.value].down = label
  //新增考试接口缓存
  if(!istype.value){
    let obj1 = {}
    list.value.forEach(item => {
      if(item.down){
        obj1[item.id] = {
          after:0,
          answer: item.answer,
          down: item.down,
        }
      }

    })
    addStorageApi({
      userId: Number(useStore.uid),
      categoryId: Number(categoryId.value),
      storageKey:`order${Number(isotype.value+1)}`,
      storageValue: JSON.stringify(obj1),
    })
  }
  //如果顺序练习，则新增顺序练习记录
  if(isotype.value === 1){
    subject.getSubjectRecordAdd({
      userId: Number(useStore.uid),
      answer: label,
      subjectId: item.id,
      subjectType: 1,
    }).then(res => {
      console.log('新增顺序练习记录', res)
    })
  }
  //如果是我的错题,答对清除错题缓存
  if(istype.value === 4&&label === list.value[currentIndex.value].answer){
    if(isShowError.value) {
      addCollectCuoTi()
      return
    }
  }
  //判断是否答对
  if(label === list.value[currentIndex.value].answer){
    if(currentIndex.value >= list.value.length-1) return uni.showModal({
      title: '提示',
      content: '已是最后一题',
      success: (res) => {
        if (res.confirm) {
        } else if (res.cancel) {
        }
      }
    })
    currentIndex.value++
  }else {
    //错题新增接口缓存
    if(istype.value) return
    const obj = storageArr.value.find(item => item.storageKey === "errorids2")
    let arr = []
    if(obj) {
      arr = JSON.parse(obj.storageValue)
      arr = [...arr, list.value[currentIndex.value].id]
      arr =  [...new Set(arr)]
    }
    subject.getSubjectPractice({
      userId: Number(useStore.uid),
      categoryId: Number(categoryId.value),
      storageKey: 'errorids2',
      storageValue: JSON.stringify(arr),
    }).then(res => {
       const index = storageArr.value.findIndex(item => item.storageKey === "errorids2")
       if(index>=0){
         storageArr.value[index].storageValue = JSON.stringify(arr)
       }
    })
  }
}
//获取当前题目
const getQuestions = async () => {
  const res = await  subject.getSubject({uid: useStore.uid,cateid:categoryId.value })
  if (res.code === 0) {
    count.value = res.count || 0
    //顺序练习
    list.value = res.data.question_list || []
    //随机练习
    if(isotype.value === 2){
      list.value = shuffleArray(list.value)
    }
    list.value.forEach(item => {
      item.down = ''
      item.collect = false
    })
    //试题缓存回显
    if(order2List.value.id&&istype.value !== 4){
      let obj2 = JSON.parse(order2List.value.storageValue)
      if(obj2) {
        for (let key in obj2) {
          list.value.forEach(item => {
               if(item.id === Number(key)&&item.down===''){
                 item.down = obj2[key].down
               }
          })
        }
      }
    }
    //然后跳转到回显的题目
    const index = findLastIndex(list.value, item => item.down!== '');
    if(index>=0&&isotype.value===1&&!istype.value){
      nextTick(() => {
        currentIndex.value = index
        if(notify.value){
          notify.value.warning ('已自动跳转到上次答题的题目')
        }

      })
    }
    //查询缓存中的收藏回显
    const obj = storageArr.value.find(item => item.storageKey === "starids2")
    if(obj){
      let arr = JSON.parse(obj.storageValue)
      if(arr.length>0){
        list.value.forEach(item => {
            arr.forEach(idx => {
              if(item.id === Number(idx)){
                item.collect = true
              }
            })
        })
      }
    }
    //我的收藏
    if(istype.value === 3){
      //合并随机练习和顺序练习试题回显
      const obj3 = storageArr.value.find(item => item.storageKey === "order3")
      if(obj3) {
        const arr3 = JSON.parse(obj3?.storageValue)
        for (let key in arr3) {
          list.value.forEach(item => {
            if(item.id === Number(key)&&item.down===''){
              item.down = arr3[key].down
            }
          })
        }
      }
      list.value = list.value.filter(item => item.collect === true)
    }
    //我的错题
    if(istype.value === 4) {
      const obj3 = storageArr.value.find(item => item.storageKey === "errorids2")
      if(obj3){
        let arr = JSON.parse(obj3.storageValue)
        if(arr.length>0){
          arr = arr.map(String)
          list.value = list.value.filter(item => arr.includes((item.id).toString()))
        }else {
          list.value = []
        }
      }
    }
    console.log('题目列表', list.value)
  }
}
//获取接口缓存的记录
const getStorageApi = async () => {
  const res = await subject.getSubjectPracticeList({
    userId: Number(useStore.uid),
    categoryId: Number(categoryId.value),
  })
  if (res.code === 0) {
    storageArr.value = res.data || []
      const index1 = storageArr.value.findIndex(item => item.storageKey === `order${Number(isotype.value+1)}`)
      if(index1 === -1) {
        storageArr.value.push(
            {
              storageKey: `order${Number(isotype.value + 1)}`,
              storageValue: JSON.stringify([]),
            }
        )
      }
      const index2 = storageArr.value.findIndex(item => item.storageKey === 'errorids2')
      if(index2 === -1) {
        storageArr.value.push(
            {
              storageKey: 'errorids2',
              storageValue: JSON.stringify([]),
            }
        )
      }
      const index3 = storageArr.value.findIndex(item => item.storageKey ==='starids2')
      if(index3 === -1) {
        storageArr.value.push(
            {
              storageKey:'starids2',
              storageValue: JSON.stringify([]),
            }
        )
      }
    console.log('接口缓存', storageArr.value)
  }
}
//收藏题目
const addCollect = async () => {
  list.value[currentIndex.value].collect = !list.value[currentIndex.value].collect
  let collectArr = list.value.filter(item => item.collect === true).map(item => item.id)
  addStorageApi({
    userId: Number(useStore.uid),
    categoryId: Number(categoryId.value),
    storageKey: 'starids2',
    storageValue: JSON.stringify(collectArr),
  })
}
//切换选项卡的回调
function onTabChange(e) {
  tabIndex.value = e.index
}
//清空记录
function clearRecord() {
  uni.showModal({
    title: '',
    content: '确定清空记录？',
    success: (res) => {
      if (res.confirm) {
        showDialog.value=false
        list.value.forEach(item => {
          item.down = ''
        })
        currentIndex.value = 0
        addStorageApi({
          userId: Number(useStore.uid),
          categoryId: Number(categoryId.value),
          storageKey: `order${Number(isotype.value+1)}`,
          storageValue: JSON.stringify([]),
        })
      }else if (res.cancel) {
      }
    }
  })
}
//清空收藏
function clearShoucang() {
  uni.showModal({
    title: '',
    content: '确定清空收藏？',
    success: (res) => {
      if (res.confirm) {
        showDialog.value=false
        list.value.forEach(item => {
          item.collect = false
        })
        subject.getSubjectPractice({
          userId: Number(useStore.uid),
          categoryId: Number(categoryId.value),
          storageKey: 'starids2',
          storageValue: JSON.stringify([]),
        }).then(() => {
          uni.showToast({
            title: '清空成功',
            icon: 'success',
            duration: 1000,
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        })
        console.log('清空收藏成功')
      }else if (res.cancel) {
        console.log('取消清空')
      }
    }
  })
}
//清空错题
function clearCuoTi() {
  uni.showModal({
    title: '',
    content: '确定清空错题？',
    success: (res) => {
      if (res.confirm) {
        showDialog.value=false
        list.value.forEach(item => {
          if(item.down&&item.down != item.answer){
            item.down = ''
          }
        })
        subject.getSubjectPractice({
          userId: Number(useStore.uid),
          categoryId: Number(categoryId.value),
          storageKey: 'errorids2',
          storageValue: JSON.stringify([]),
        }).then(() => {
          uni.showToast({
            title: '清空成功',
            icon: 'success',
            duration: 1000,
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        })
        console.log('清空错题成功')
      }else if (res.cancel) {
        console.log('取消清空')
      }
    }
  })
}
//清除单个错题
const addCollectCuoTi = async () => {
  if(list.value.length === 0) return
  list.value[currentIndex.value].down = ''
  let errorArr = list.value.filter(item=>item.id !== list.value[currentIndex.value].id).map(item => item.id)
  subject.getSubjectPractice({
    userId: Number(useStore.uid),
    categoryId: Number(categoryId.value),
    storageKey: 'errorids2',
    storageValue: JSON.stringify(errorArr),
  }).then(() => {
    const index = list.value.findIndex(item => item.id === list.value[currentIndex.value].id)
    list.value.splice(index,1)
    if(currentIndex.value!==0) {
      currentIndex.value--
    }
    // uni.showToast({
    //   title: '清除成功',
    //   icon: 'success',
    //   duration: 1000,
    // })
    setTimeout(() => {
      if(errorArr.length===0){
        uni.navigateBack()
      }
    }, 1000)
  })

}
//获取最后一题的索引
function findLastIndex(array, predicate) {
  let index = array.length;
  while (index--) {
    if (predicate(array[index])) return index;
  }
  return -1;
}
//打乱数组
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}
</script>
<style scoped lang="scss">
.top10{
    top: -6rpx;
}
/* 定义向左下旋转的动画 */
@keyframes rotateToLeftDown {
  0% {
    transform: translateX(0) rotate(20deg); /* 初始位置：不移动，不旋转 */
  }
  100% {
    transform: rotate(-45deg); /* 向左移动并顺时针旋转 45 度 */
  }
}

/* 向左下旋转的图片 */
.zuo {
  animation: rotateToLeftDown 2s infinite ease-in-out;
}

</style>